package cn.kgc.javaweb.servlet;

import cn.kgc.javaweb.entity.User;
import cn.kgc.javaweb.service.UserService;
import cn.kgc.javaweb.service.impl.UserServiceImpl;
import cn.kgc.javaweb.util.DruidUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author: mosin
 * @version: v1.0  2022/10/30
 * 处理用户登录请求的servlet
 */
@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {

    private UserService userService  = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1.获取请求参数  key  username  password   对应表单中的name属性的值
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = User.builder().username(username).password(password).build();

        // 调用业务层判定 用户是否登录成功
        Boolean b = userService.login(user);

        if(b){
            // 跳转主页  重定向   /javaweb/index.jsp
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
            return;
        }
        // 通过转发的方式 跳转页面到登录页
        req.setAttribute("info", "用户名或者密码错误");
        req.getRequestDispatcher("/login.jsp").forward(req, resp);

    }
}
